package com.workingpub.commons.jdbc.builder.internal;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.workingpub.commons.jdbc.builder.BuildContext;
import com.workingpub.commons.jdbc.builder.ResolverFactory;
import com.workingpub.commons.jdbc.builder.SqlMappingBuilder;

@Service("sqlMappingBuilder")
public class DefaultSqlMappingBuilder implements SqlMappingBuilder {
	private static final Logger logger = LoggerFactory.getLogger(DefaultSqlMappingBuilder.class);

	@Autowired
	private ResolverFactory resolverFactory;

	@Override
	public void build(BuildContext context) {
		Assert.notNull(context, "BuildContext instance is null.");
		Assert.notNull(context.getSqlMapping(), "Build sql mapping, the SqlMapping instance is null.");
		// Assert.notNull(context.getReturnType(), "Build sql mapping, the
		// return type is null.");
		Assert.isTrue(!CollectionUtils.isEmpty(context.getSqlMapping().getContent()),
				"Build sql mapping, the mapping context is empty : " + context.getSqlMapping().getId());

		logger.debug("Start to build sql mapping : " + context.getSqlMapping().getId());
		List<Object> results = resolverFactory.resolve(context, context.getSqlMapping().getContent().toArray());
		for (Object entry : results) {
			Assert.isTrue(entry instanceof String, "Failed to resolve entry : " + entry);
			String sqlSegment = (String) entry;
			if (StringUtils.hasText(sqlSegment)) {
				context.appendSqlSegment(sqlSegment);
			}
		}
		logger.debug("Completed to build sql mapping : " + context.getSqlMapping().getId());
		logger.debug("Source sql : \n{}", context.getSourceSql());
		logger.debug("Source params : \n{}", context.getSourceParams());
	}
}
